var editor; // use a global for the submit and return data rendering
var table;
var userTypeId = 0;
var user;
var communityId="";
function getUrl(url,params) {
    for (var i=0;i<params.length;i++){
        if ($("#"+params[i]).val()!= "") {
            url = url + "&"+params[i]+"=" + $("#"+params[i]).val();
        }
    }
    return url;

}
$(document).ready(function () {
    $.ajax({
        url: '/commis/api/user/currentUser',
        type: "GET",
        async: false,
        dataType: 'json',
        data: {},
        success: function (response) {
            if (response.status == 0) {
                console.log("用户存在");
                user = response.data;
                userTypeId = user.userTypeId;
                if(userTypeId==4){
                    communityId=user.communityId;
                }
                console.log(userTypeId);
            } else if (response.status == 1) {
                alert("登录用户已经过期，请重新登录");
                window.parent.location.href = "../../login.html";
            }
        }, error: function (msg) {
            alert("登录用户已经过期，请重新登录");
            window.parent.location.href = "../../login.html";
        }
    })

    $.ajax({
        url: '/commis/api/community/all',
        async: false,
        dataType: 'json',
        success: function (response) {
            for (var i = 0; i < response.length; i++) {
                $("#community").append("<option value='" + response[i].communityId + "'>" + response[i].communityName + "</option>");
            }

        }, error: function () {
            alert("发生错误");
            window.parent.location.href = "../../login.html";
        }
    });


    $.ajax({
        url: "/commis/api/setting/getValueByName",
        type: "GET",
        async: false,
        dataType: 'json',
        data: {

            name:"固定资产"

        },
        success: function (response) {
            if (response.status==0) {

                var value =response.data;
                var fields= [
                    {
                        label: "propertyState:",
                        name: "propertyState",
                        type: "hidden",

                    },
                    {
                        label: "isDelete:",
                        name: "isDelete",
                        type: "hidden",
                    },
                    {
                        label: "所属社区:",
                        name: "communityId",
                        type: "select"
                    },
                    {
                        label: "资产编号:",
                        name: "propertyCode"
                    }, {
                        label: "资产名称:",
                        name: "propertyName"
                    },{
                        label: "购置日期:",
                        name: "deployTime",
                        type: 'datetime',
                        def: function () {
                            return new Date();
                        }
                    }, {
                        label: "品牌:",
                        name: "propertyBrand"
                    }, {
                        label: "规格型号:",
                        name: "specificationType"
                    }, {
                        label: "资产序号:",
                        name: "serialNumber"
                    }, {
                        label: "数量:",
                        name: "count"
                    }, {
                        label: "配置来源:",
                        name: "configurationUnit"
                    }, {
                        label: "存放地点:",
                        name: "propertyAdd"
                    }, {
                        label: "用途:",
                        name: "useStatus"
                    }, {
                        label: "备注:",
                        name: "remarks"
                    },{
                        label: "类别:",
                        name: "typeId",
                        type: "select"
                    }
                ]
                if(userTypeId==4){
                    fields= [
                        {
                            label: "所属社区:",
                            name: "community.communityName",
                            type:"readonly",
                            def: function () {
                                return  user.community.communityName;
                            }

                        },
                        {
                            label: "propertyState:",
                            name: "propertyState",
                            type: "hidden",
                        },
                        {
                            label: "isDelete:",
                            name: "isDelete",
                            type: "hidden",
                        },
                        {
                            label: "资产编号:",
                            name: "propertyCode"
                        }, {
                            label: "资产名称:",
                            name: "propertyName"
                        },{
                            label: "购置日期:",
                            name: "deployTime",
                            type: 'datetime',
                            def: function () {
                                return new Date();
                            }
                        }, {
                            label: "品牌:",
                            name: "propertyBrand"
                        }, {
                            label: "规格型号:",
                            name: "specificationType"
                        }, {
                            label: "资产序号:",
                            name: "serialNumber"
                        }, {
                            label: "数量:",
                            name: "count"
                        }, {
                            label: "配置来源:",
                            name: "configurationUnit"
                        }, {
                            label: "存放地点:",
                            name: "propertyAdd"
                        }, {
                            label: "用途:",
                            name: "useStatus"
                        }, {
                            label: "备注:",
                            name: "remarks"
                        },{
                            label: "类别:",
                            name: "typeId",
                            type: "select"
                        }]
                }
                editor = new $.fn.dataTable.Editor({
                    ajax: {
                        create: {
                            type: 'POST',
                            url: '/commis/api/property/create'
                        },
                        edit: {
                            type: 'PUT',
                            url: '/commis/api/property/edit?id=_id_'
                        },
                        remove: {
                            type: 'DELETE',
                            url: '/commis/api/property/remove?id=_id_'
                        }
                    },
                    i18n: {
                        create: {
                            title: "申报资产",
                            submit: "确定"
                        },
                        edit: {
                            title: "修改记录",
                            submit: "修改",
                            confirm: "您确定要修改这 %d 条记录吗?"
                        },
                        remove: {
                            title: "删除记录",
                            submit: "删除",
                            confirm: "您确定要删除这 %d 条记录吗?"
                        }
                    },
                    idSrc: 'propertyId',
                    table: "#propertyTable",
                    fields:fields
                });

                var buttons = [];
                var select = true;
                if (userTypeId == 1) {
                    $(".communityDiv").show();
                    select = true;
                    buttons = [
                        {extend: "create", editor: editor, text: "添加", className: 'btn btn-primary'},
                        {extend: "edit", editor: editor, text: "修改", className: 'btn btn-primary'},
                        {extend: "remove", editor: editor, text: "删除", className: 'btn btn-danger'}
                    ];
                    console.log(buttons);


                } else if (userTypeId == 2) {
                    $(".communityDiv").show();
                    select = true;
                    buttons = [
                        {extend: "edit", editor: editor, text: "修改", className: 'btn btn-primary'},
                        {extend: "remove", editor: editor, text: "删除", className: 'btn btn-danger'}
                    ];

                } else if (userTypeId == 3||userTypeId == 6||userTypeId == 7||userTypeId == 8||userTypeId == 9) {
                    $(".communityDiv").show();
                    select = false;
                    buttons = [];

                } else if (userTypeId == 4) {
                    $(".communityDiv").hide();
                    select = true;

                    if(value==1){
                        buttons = [
                            {extend: "create", editor: editor, text: "申报", className: 'btn btn-primary'},{
                                extend: "selectedSingle",
                                text: "撤销申报",
                                className: 'btn btn-primary',
                                action: function ( e, dt, node, config ) {

                                    editor
                                        .edit( table.row( { selected: true } ).index() ,false);

                                    var propertyState = editor.get('propertyState');
                                    if(propertyState!=0){
                                        alert("当前资产状态不是待审核状态，不能撤销！");
                                        return false;
                                    }
                                    editor.set('isDelete', '1');
                                    editor.submit();

                                }
                            },
                            {
                                extend: "selectedSingle",
                                text: "申请报废",
                                className: 'btn btn-primary',
                                action: function ( e, dt, node, config ) {

                                    editor
                                        .edit( table.row( { selected: true } ).index(),false);
                                    var propertyState = editor.get('propertyState');
                                    if(propertyState!=1){
                                        alert("当前资产状态不是在用状态，不能申请报废！");
                                        return false;
                                    }
                                    editor.set('propertyState', '2');
                                    editor.submit();

                                }
                            },
                            {
                                extend: "selectedSingle",
                                text: "撤销报废",
                                className: 'btn btn-primary',
                                action: function ( e, dt, node, config ) {

                                    editor
                                        .edit( table.row( { selected: true } ).index() ,false);

                                    var propertyState = editor.get('propertyState');
                                    if(propertyState!=2){
                                        alert("当前资产状态不是待报废状态，不能撤销！");
                                        return false;
                                    }
                                    editor.set('propertyState', '1');
                                    editor.submit();

                                }
                            },
                            {extend: "edit", editor: editor, text: "修改", className: 'btn btn-primary'}

                        ]
                    }else{
                        buttons = [
                            {extend: "create", editor: editor, text: "申报", className: 'btn btn-primary'},{
                                extend: "selectedSingle",
                                text: "撤销申报",
                                className: 'btn btn-primary',
                                action: function ( e, dt, node, config ) {

                                    editor
                                        .edit( table.row( { selected: true } ).index() ,false);

                                    var propertyState = editor.get('propertyState');
                                    if(propertyState!=0){
                                        alert("当前资产状态不是待审核状态，不能撤销！");
                                        return false;
                                    }
                                    editor.set('isDelete', '1');
                                    editor.submit();

                                }
                            },
                            {
                                extend: "selectedSingle",
                                text: "申请报废",
                                className: 'btn btn-primary',
                                action: function ( e, dt, node, config ) {

                                    editor
                                        .edit( table.row( { selected: true } ).index(),false);
                                    var propertyState = editor.get('propertyState');
                                    if(propertyState!=1){
                                        alert("当前资产状态不是在用状态，不能申请报废！");
                                        return false;
                                    }
                                    editor.set('propertyState', '2');
                                    editor.submit();

                                }
                            },
                            {
                                extend: "selectedSingle",
                                text: "撤销报废",
                                className: 'btn btn-primary',
                                action: function ( e, dt, node, config ) {

                                    editor
                                        .edit( table.row( { selected: true } ).index() ,false);

                                    var propertyState = editor.get('propertyState');
                                    if(propertyState!=2){
                                        alert("当前资产状态不是待报废状态，不能撤销！");
                                        return false;
                                    }
                                    editor.set('propertyState', '1');
                                    editor.submit();

                                }
                            }

                        ]
                    }
                }else if (userTypeId ==5) {
                    $(".communityDiv").hide();
                    select = false;
                    buttons = [];

                }

                table = $('#propertyTable').DataTable({

                    dom: "Bfrtip",
                    ajax: "/commis/api/property/pageDatatables?communityId="+communityId,
                    autoWidth: true,
                    responsive: true,

                    serverSide: true,
                    processing: true,
                    lengthChange: false,//是否允许用户改变表格每页显示的记录数
                    ordering: false,//是否允许用户排序
                    paging: true,//是否分页
                    pagingType: "full_numbers",//除首页、上一页、下一页、末页四个按钮还有页数按钮
                    searching: false,//是否开始本地搜索
                    stateSave: false,//刷新时是否保存状态
                    autoWidth: true,//自动计算宽度
                    createdRow: function ( row, data, index ) {
                        if ( data["propertyState"] == 0|| data["propertyState"]==2) {
                            // $('td', row).css("color","red");
                            // $('td', row).css('backgroundColor','#FF0000')
                            // $('td', row).eq(3).css('font-weight',"bold").css("color","red");
                            $('td', row).css('backgroundColor', '#f8c4c4');
                            // $('tr', row).css("color","red");
                        }
                    },
                    language: {
                        emptyTable: "没有数据",
                        search: "搜索:",
                        paginate: {
                            first: "首页",
                            previous: "上一页",
                            next: "下一页",
                            last: "尾页"

                        },
                        select: {
                            rows: {
                                _: "选中 %d 行",
                                1: "选中 1 行"
                            },
                            columns: "选中 %d 列"
                        },
                        lengthMenu: "每页 _MENU_ 条记录",
                        zeroRecords: "没有找到记录",
                        info: "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )，共 _TOTAL_ 项",
                        infoEmpty: "无记录",
                        infoFiltered: "(从 _MAX_ 条记录过滤)"
                    },
                    columns: [
                        {
                            data: 'community.communityName', defaultContent: ""
                        },
                        /*    {
                         data: 'depart.departName', defaultContent: ""
                         },*/
                        {
                            data: 'propertyCode', defaultContent: ""
                        }, {
                            data: 'propertyName', defaultContent: ""

                        }, {
                            data: 'deployTime', defaultContent: ""
                        }, {
                            data: 'propertyBrand', defaultContent: ""
                        }, {
                            data: 'specificationType', defaultContent: ""
                        }, {
                            data: 'serialNumber', defaultContent: ""
                        }, {
                            data: 'count', defaultContent: ""
                        }, {
                            data: 'configurationUnit', defaultContent: ""
                        }, {
                            data: 'propertyAdd', defaultContent: ""
                        }, {
                            data: 'propertyState',
                            render: function (data, type, row) {
                                // Combine the first and last names into a single table field
                                if(0==data){
                                    return "待审批";
                                }else if(1==data){
                                    return "在用"
                                }else if(2==data){
                                    return "待报废"
                                }else if(3==data){
                                    return "已报废"
                                }else{
                                    return "不同意"
                                }
                            }
                        }, {
                            data: 'useStatus', defaultContent: ""
                        }, {
                            data: 'remarks', defaultContent: ""
                        }, {
                            data: 'propertyType.typeName', defaultContent: ""
                        }
                    ],
                    select: select,
                    buttons:  buttons

                });





            } else if (response.status==1) {
                alert("没有数据");
            }
        },error: function (msg) {
            alert("发生错误了");
        }
    })


    $('#search').on('click', function () {

        var url = "/commis/api/property/pageDatatables?1=1"

        if(userTypeId!=4){
            communityId = $('#community').val();

        }
        url = url + "&communityId=" + communityId;
        var params=["propertyCode","propertyName","configurationUnit","deployTime","propertyAdd","propertyState","propertyQueryType","orderName"];
        url=getUrl(url,params);


        table.ajax.url(url).load();
    });


});

$(function () {
    $("#page_style").frame({
        float: 'left',
        menu_nav: '.Quick_operation',
        color_btn: '.skin_select',
        Sellerber_menu: '.list_content',
        Sellerber_header: '.Sellerber_header',
    });
});
$("#iframe_box").niceScroll({
    cursorcolor: "#888888",
    cursoropacitymax: 1,
    touchbehavior: false,
    cursorwidth: "5px",
    cursorborder: "0",
    cursorborderradius: "5px"
});

require.config({
    paths: {
        echarts: './js/dist'
    }
});
	
